package com.start.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.start.common.constant.StartConstant;
import com.start.common.details.BaseUserDetails;
import com.start.common.tools.IPTools;
import com.start.common.tools.SpringContextTools;
import com.start.core.entity.StartLogEntity;
import com.start.core.mappers.StartLogMapper;
import com.start.core.service.StartLogService;
import com.start.security.StartTokenTools;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;

@Service
public class StartLogServiceImpl extends ServiceImpl<StartLogMapper, StartLogEntity> implements StartLogService, StartConstant.LogType {

    @Override
    public void createUserLoginLog(BaseUserDetails userDetails) {
        StartLogEntity startLogEntity = createLog("用户登录", "登录", USER_LOGIN);
        startLogEntity.setCreateBy(userDetails.getUserId());
        save(startLogEntity);
    }


    @Override
    public void createUserLoginOutLog() {
        final BaseUserDetails currentUser = StartTokenTools.getCurrentUser();
        if (currentUser == null) return;
        StartLogEntity startLogEntity = createLog("注销登录", "注销登录", USER_LOGIN_OUT);
        startLogEntity.setCreateBy(currentUser.getUserId());
        save(startLogEntity);
    }

    private StartLogEntity createLog(String title, String action, int logType) {
        StartLogEntity startLogEntity = new StartLogEntity();
        HttpServletRequest httpServletRequest = SpringContextTools.getHttpServletRequest();
        startLogEntity.setRequestIp(IPTools.getIpAddr(httpServletRequest));
        startLogEntity.setTitle(title);
        startLogEntity.setAction(action);
        startLogEntity.setLogType(logType);
        startLogEntity.setRequestMethod(httpServletRequest.getMethod().toLowerCase());
        return startLogEntity;
    }
}
